package com.lgd.factoryattendance.Activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Activity.editActivity.EditAssembleActivity;
import com.lgd.factoryattendance.Activity.editActivity.EditDebugActivity;
import com.lgd.factoryattendance.Bean.AssemblyManagement;
import com.lgd.factoryattendance.Bean.CustomSpinnerBean;
import com.lgd.factoryattendance.Bean.ElectricSpinnerBean;
import com.lgd.factoryattendance.Bean.ElectricalProcess;
import com.lgd.factoryattendance.Bean.FactoryDeviceManagement;
import com.lgd.factoryattendance.Bean.MachineSpinnerBean;
import com.lgd.factoryattendance.Bean.ProjectInfoVo;
import com.lgd.factoryattendance.Bean.ProjectManagement;
import com.lgd.factoryattendance.Bean.ProjectSpinner;
import com.lgd.factoryattendance.Bean.ProjectType;
import com.lgd.factoryattendance.Bean.SysDept;
import com.lgd.factoryattendance.Bean.SysUser;
import com.lgd.factoryattendance.Bean.WorkClockType;
import com.lgd.factoryattendance.Bean.WorkHourStatistics;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.NoDoubleClickUtil;
import com.lgd.factoryattendance.Utils.ScreenUtils;
import com.lgd.factoryattendance.Utils.TimeUtils;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.adapter.CustomSpinnerAdapter;
import com.lgd.factoryattendance.adapter.ElectricSpinnerAdapter;
import com.lgd.factoryattendance.adapter.MachineSpinnerAdapter;
import com.lgd.factoryattendance.adapter.MyAdapter;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IResponse;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;

import java.io.IOException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import q.rorbin.badgeview.QBadgeView;

public class HomePageActivity extends BaseActivity implements View.OnClickListener{
    ImageView workOrder_IV ,debugLog_IV ,adminManager_IV,iv_notice ,iv_refresh, iv_delect_punch,iv_home_refresh;
    TextView name_TV, group_TV, swipeTime_TV,downTime_TV,tv_starttimeFill,tv_durationFill,tv_device_number;
    EditText cardNumber_ET;
    private TextToSpeech textToSpeech = null;//创建自带语音对象
    private String scanResult;  // 扫描结果
    Intent serviceIntent;
    boolean is = false;   //是否管理员刷卡
    SysUser sysUser2;
    private ArrayList<CustomSpinnerBean> customSpinnerBeanArrayList = null;
    Long userId, deptId, fill_userID;    // 部门id
    String starttime, nickName, deptName, duration, clockType, idCard, androidId, str_clockType;
    LinearLayout downTime_layout,layout_close;
    Boolean durationType =false , popClose = false;
    QBadgeView badgeView;
    private static final String TAG = "HomePageActivity";
    Spinner sp_projectType, sp_projectName ,sp_electricAssembly,sp_machineAssembly, sp_clockType ;
    private final List<ProjectSpinner> projectnameList = new ArrayList<>();  // 项目 列表
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        init();
        initTTS();
        initActivityResult();

    }
    public void init(){
        menu_pop = new PopupWindow(getApplicationContext());
        androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        tv_device_number = findViewById(R.id.tv_device_number);
        tv_device_number.setText(androidId);
        iv_home_refresh = findViewById(R.id.iv_home_refresh);
        iv_home_refresh.setOnClickListener(this);
//        sp_projectName = findViewById(R.id.sp_projectName);
//        sp_projectType = findViewById(R.id.sp_projectType);
        iv_delect_punch = findViewById(R.id.iv_delect_punch);
        iv_delect_punch.setOnClickListener(this);
        layout_close = findViewById(R.id.layout_close);
        layout_close.setOnClickListener(this);
        badgeView = new QBadgeView(getApplicationContext());   // 角标
        iv_notice = findViewById(R.id.iv_notice);
        iv_notice.setOnClickListener(this);
        badgeView.bindTarget(iv_notice);  // 视图不能为null
        name_TV = findViewById(R.id.name_TV);
        group_TV = findViewById(R.id.group_TV);
        cardNumber_ET = findViewById(R.id.cardNumber_ET);
        CloseInput(cardNumber_ET);//        //  设置 edittext有光标但不弹出软键盘
        swipeTime_TV = findViewById(R.id.swipeTime_TV);
        workOrder_IV = findViewById(R.id.workOrder_IV);
        workOrder_IV.setOnClickListener(this);
        debugLog_IV = findViewById(R.id.debugLog_IV);
        debugLog_IV.setOnClickListener(this);
        adminManager_IV = findViewById(R.id.adminManager_IV);
        adminManager_IV.setOnClickListener(this);
        setAdminIDcard();
        // 扫描 信息
        cardNumber_ET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE ||
                        event.getAction() == KeyEvent.ACTION_DOWN &&
                                event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    closeEditText(cardNumber_ET);
                    // 处理扫描结果
                    scanResult = cardNumber_ET.getText().toString();
                    System.out.println("----刷卡了-----"+scanResult);
                    if (scanResult.length() == 10){
                        if (scanResult.equals(idCard)){             // 判断管理员卡片号
                            setView();
                        }else {
                            setSeleceStaffInfo(scanResult);
                        }
                    }else if (scanResult.length() == 20){
                        if (scanResult.substring(10,20).equals(idCard)){
                            setView();
                        }else {
                            setSeleceStaffInfo(scanResult.substring(10,20));
                        }
                    }else {
                        cardNumber_ET.setText("");
                    }
                    return true;
                }
                return false;
            }
        });
//         启动前台服务
//        serviceIntent = new Intent(this, KeepLiveService.class);
//        startService(serviceIntent);
        //  部门下拉框 数据
        findDeptByDu();

    }
    public void setView (){
        cardNumber_ET.setText("");
        if (!is){
            popStaff();
            setAlpha(0.2f);
            swipeTime_TV.setText("");
            name_TV.setText("");
            group_TV.setText("");
            is = true;
        }
    }
    public void setSeleceStaffInfo(String scanResult){
        cardNumber_ET.setText(scanResult);
        swipeTime_TV.setText(TimeUtils.getCurrentDateTime());
        SysUser sysUser = new SysUser();
        sysUser.setIcCard(scanResult);
        seleceStaffInfo(sysUser);
    }
    //  其他页面返回 刷新 界面
    private ActivityResultLauncher launcher;
    public void initActivityResult() {
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Log.d(TAG, "onActivityResult: ----返回来了---: "+result.getResultCode());
                if (result.getResultCode() != 0){
                    reStartActivity();
                }
            }
        });
    }

    PopupWindow swipeCardInfo_pop;
    String punchType_str = "";
    Long user_deptid ;
    LinearLayout layout_machnie, layout_electrical,layout_clockType, layout_electric_code;
    TextView tv_selectProject;
    RadioButton mechanical_assembly_RB;
    RadioGroup rg_electric_code;
//    刷卡信息弹窗
    @SuppressLint("SetTextI18n")
    public void popSwipeCardInfo(){
        punchType_str = "机械装配";
        View swipeCardInfo_view = getLayoutInflater().inflate(R.layout.swipe_card_pop,null);
        TextView popName_TV = swipeCardInfo_view.findViewById(R.id.popName_TV);
        TextView popGroup_TV = swipeCardInfo_view.findViewById(R.id.popGroup_TV);
        TextView popSwipeTime_TV = swipeCardInfo_view.findViewById(R.id.popSwipeTime_TV);
        tv_selectProject = swipeCardInfo_view.findViewById(R.id.tv_selectProject);

        sp_electricAssembly = swipeCardInfo_view.findViewById(R.id.sp_electricAssembly);
        sp_machineAssembly = swipeCardInfo_view.findViewById(R.id.sp_machineAssembly);
        sp_clockType = swipeCardInfo_view.findViewById(R.id.sp_clockType);
        layout_machnie = swipeCardInfo_view.findViewById(R.id.layout_machnie);
        layout_electrical = swipeCardInfo_view.findViewById(R.id.layout_electrical);
        layout_clockType = swipeCardInfo_view.findViewById(R.id.layout_clockType);
        layout_electric_code = swipeCardInfo_view.findViewById(R.id.layout_electric_code);

        iv_refresh = swipeCardInfo_view.findViewById(R.id.iv_refresh);
        iv_refresh.setOnClickListener(this);
        sp_projectName = swipeCardInfo_view.findViewById(R.id.sp_projectName);
        sp_projectType = swipeCardInfo_view.findViewById(R.id.sp_projectType);
        projectType();
        mechanical_assembly_RB = swipeCardInfo_view.findViewById(R.id.mechanical_assembly_RB);
        //  动态添加 单选按钮
        rg_electric_code = swipeCardInfo_view.findViewById(R.id.rg_electric_code);

        RadioGroup punchType_RG = swipeCardInfo_view.findViewById(R.id.punchType_RG);   // 单选框
        Button clockInSubmit_Bt = swipeCardInfo_view.findViewById(R.id.clockInSubmit_Bt);
        ImageView iv_close = swipeCardInfo_view.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swipeCardInfo_pop.dismiss();
            }
        });
        popName_TV.setText(name_TV.getText().toString());
        popGroup_TV.setText(group_TV.getText().toString());
        popSwipeTime_TV.setText(swipeTime_TV.getText().toString());

        punchType_RG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = swipeCardInfo_view.findViewById(checkedId);
                punchType_str = radioButton.getText().toString();
                Log.d(TAG, "onCheckedChanged: ------打卡 类型------"+punchType_str);
                switch (punchType_str){
                    case "机械装配":
                        layout_machnie.setVisibility(View.VISIBLE);
                        layout_clockType.setVisibility(View.GONE);
                        layout_electrical.setVisibility(View.GONE);
                        layout_electric_code.setVisibility(View.GONE);
                        electricAssemblyId = 0L;

                        machineAssemblyId = 0L;
                        break;
                    case "电气装配":
                        layout_machnie.setVisibility(View.GONE);
                        layout_clockType.setVisibility(View.GONE);
                        layout_electrical.setVisibility(View.VISIBLE);
                        layout_electric_code.setVisibility(View.VISIBLE);
                        machineAssemblyId = 0L;

                        electricAssemblyId = 0L;
                        break;
                    case "其他工作":
                        layout_machnie.setVisibility(View.GONE);
                        layout_electrical.setVisibility(View.GONE);
                        layout_clockType.setVisibility(View.VISIBLE);
                        layout_electric_code.setVisibility(View.GONE);
                        ProjectManagement p = new ProjectManagement();
                        selectAssemblyById(p);
                        break;
                    default:
                        layout_machnie.setVisibility(View.GONE);
                        layout_electrical.setVisibility(View.GONE);
                        layout_clockType.setVisibility(View.GONE);
                        layout_electric_code.setVisibility(View.GONE);
                        break;
                }
            }
        });
        int width = ScreenUtils.getWidth(HomePageActivity.this);
        swipeCardInfo_pop = new PopupWindow
                (swipeCardInfo_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        swipeCardInfo_pop.setTouchable(true);
        swipeCardInfo_pop.setFocusable(true);
        swipeCardInfo_pop.setOutsideTouchable(true);
        swipeCardInfo_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
        clockInSubmit_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                WorkHourStatistics w = new WorkHourStatistics();
                w.setUpperSerialNo(androidId);
                w.setProducedate(TimeUtils.getCurrentDate());
                w.setUserid(userId);
//                w.setStarttime(swipeTime_TV.getText().toString());

                if (punchType_str.equals("车间整理") || punchType_str.equals("其他工作")){
                    if (sp_clockType.getSelectedItem() != null){
                        str_clockType = sp_clockType.getSelectedItem().toString();

                        if (str_clockType.equals("人员借用") || str_clockType.equals("电商卸货") || str_clockType.equals("其他工作") ||
                         str_clockType.equals("外贸拍视频") || str_clockType.equals("车间后勤") || punchType_str.equals("车间整理")){
                            w.setProjectId(null);
                        }else {
                            w.setProjectId(long_projectId);
                        }
                    }

                }else {
                    w.setProjectId(long_projectId);
                }
//                w.setDeptId(punchType_str.equals("机械装配") ? long_deptId : user_deptid);

                switch (punchType_str){
                    case "机械装配":
                        if ( machineAssemblyId == null || machineAssemblyId == 0 ){
                            ToastUtils.warnShowLong(getApplicationContext(),"请选择 《 机械部装 》 ");
                        }else {
                            w.setAssemblyid(machineAssemblyId);
                            w.setClocktype(punchType_str);
                            w.setDeptId(long_deptId);
                            workClockIn(w);
                        }
                        break;
                    case "电气装配":
                        if ( electricAssemblyId == null || electricAssemblyId == 0  ){
                            ToastUtils.warnShowLong(getApplicationContext(),"请选择 《 电气部装 》 与 B 码");
                        }else {
                            w.setElectricalAssemblyId(electricAssemblyId);
                            w.setClocktype(punchType_str);
                            w.setDeptId(user_deptid);
                            workClockIn(w);
                        }
                        break;
                    case "其他工作":
                        if (str_clockType.equals("请选择类型") || str_clockType.equals("")){
                            ToastUtils.warnShowLong(getApplicationContext(),"您还没选择打卡类型！！！");
                        }else {
                            w.setClocktype(str_clockType);
                            w.setDeptId(user_deptid);

                            if (str_clockType.equals("人员借用") || str_clockType.equals("电商卸货") || str_clockType.equals("其他工作") ||
                                    str_clockType.equals("外贸拍视频") || str_clockType.equals("车间后勤")
                                    || punchType_str.equals("车间整理")){    // 无需项目
                                workClockIn(w);
                            }else {
                                if (long_projectId == null){
                                    ToastUtils.warnShowLong(getApplicationContext(),"请选择项目！！！");
                                }else {
                                    workClockIn(w);
                                }
                            }
                        }
                        break;
                    case "电气调试": case "机械调试":
                        if (long_projectId == null){
                            ToastUtils.warnShowLong(getApplicationContext(),"请选择项目！！！");
                        }else {
                            w.setClocktype(punchType_str);
                            w.setDeptId(user_deptid);
                            workClockIn(w);
                        }
                        break;
                    default:
                        w.setClocktype(punchType_str);
                        w.setDeptId(user_deptid);
                        workClockIn(w);
                        break;
                }
            }
        });
    }

    public void setAbnormalClock(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setAlpha(1.0f);
                gainAbnormalSize = false;
                WorkHourStatistics w = new WorkHourStatistics();
                w.setUserid(userId);
                getAbnormalClock(w);
            }
        },500);
    }
    public void getAssemblyInfo(Long id){
        layout_machnie.setVisibility(View.VISIBLE);
        layout_electrical.setVisibility(View.GONE);
        layout_clockType.setVisibility(View.GONE);
        ProjectManagement p = new ProjectManagement();
        p.setProjectid(id);
        selectAssemblyById(p);

    }
//    补卡 弹窗
    PopupWindow staff_pop;
    ArrayAdapter<String> staff_adapter;
    public void popStaff(){
        if (staff_list.size() > 0){
            staff_list.clear();
        }
        //根据 员工姓名查找信息
        staff_list.add("选择员工");
        SysUser sysUser = new SysUser();
        seleceStaffInfo(sysUser);
        View staff_view = getLayoutInflater().inflate(R.layout.staff_pop,null);
        Spinner staff_SP = staff_view.findViewById(R.id.staff_SP);
        staff_adapter = new ArrayAdapter<>(this,R.layout.spinner_item,staff_list);
        staff_SP.setAdapter(staff_adapter);
        Button staffSubmit_BT = staff_view.findViewById(R.id.staffSubmit_BT);
        staffSubmit_BT.setOnClickListener(this);
        staffSubmit_BT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!staff_SP.getSelectedItem().toString().equals("选择员工")){
                    SysUser sysUser1 = new SysUser();
                    sysUser1.setNickName(staff_SP.getSelectedItem().toString());
                    seleceStaffInfo(sysUser1);
                    if (is){
                        staff_pop.dismiss();  // 关闭
                        is = false;
                    }
                }else {
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择员工！！！");
                }
            }
        });
        ImageView right_IV = staff_view.findViewById(R.id.right_IV);
        right_IV.setOnClickListener(new View.OnClickListener() {    // 退出
            @Override
            public void onClick(View v) {
                if (is){
                    staff_pop.dismiss();
                    setAlpha(1.0f);
                    is = false;
                }
            }
        });
        int width = ScreenUtils.getWidth(HomePageActivity.this);
        staff_pop = new PopupWindow
                (staff_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        staff_pop.setTouchable(true);
        staff_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }

    String selectDept;
    //   生产后勤打卡弹窗
    PopupWindow swipeCardInfoLogistics_pop;
    public void popSwipeCardInfoLogistics() {
        View swipeCardInfo_view = getLayoutInflater().inflate(R.layout.swipe_card_logistics_pop,null);
        int width = ScreenUtils.getWidth(getApplicationContext());
        swipeCardInfoLogistics_pop = new PopupWindow
                (swipeCardInfo_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        swipeCardInfoLogistics_pop.setTouchable(true);
        swipeCardInfoLogistics_pop.setFocusable(true);
        swipeCardInfoLogistics_pop.setOutsideTouchable(true);
        swipeCardInfoLogistics_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1.0f);
            }
        });
        TextView popName_TV = swipeCardInfo_view.findViewById(R.id.popName_TV);
        TextView popGroup_TV = swipeCardInfo_view.findViewById(R.id.popGroup_TV);
        TextView popCardNumber_TV = swipeCardInfo_view.findViewById(R.id.popCardNumber_TV);
        TextView popSwipeTime_TV = swipeCardInfo_view.findViewById(R.id.popSwipeTime_TV);
        Spinner sp_clockInType = swipeCardInfo_view.findViewById(R.id.sp_clockInType);
        ImageView iv_close = swipeCardInfo_view.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swipeCardInfoLogistics_pop.dismiss();
            }
        });
        CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(customSpinnerBeanArrayList,HomePageActivity.this);
        sp_clockInType.setAdapter(adapter);
        Button clockInSubmit_Bt = swipeCardInfo_view.findViewById(R.id.clockInSubmit_Bt);
        popName_TV.setText(name_TV.getText().toString());
        popGroup_TV.setText(group_TV.getText().toString());
        popCardNumber_TV.setText(cardNumber_ET.getText().toString());
        popSwipeTime_TV.setText(swipeTime_TV.getText().toString());
        sp_clockInType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                deptId = customSpinnerBeanArrayList.get(position).getDeptId();
                selectDept = customSpinnerBeanArrayList.get(position).getDeptName();
                ToastUtils.successShowLong(HomePageActivity.this,"您选择的打卡部门是"+selectDept);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        clockInSubmit_Bt.setOnClickListener(new View.OnClickListener() {   // 确定
            @Override
            public void onClick(View v) {
                if (NoDoubleClickUtil.isFastDoubleClick()){return;}

                WorkHourStatistics w = new WorkHourStatistics();
                w.setProducedate(TimeUtils.getCurrentDate());
                w.setUserid(userId);
                w.setUpperSerialNo(androidId);
                w.setClocktype("后勤打卡");
                w.setStarttime(swipeTime_TV.getText().toString());
                w.setDeptId(deptId);
                workClockIn(w);  // 打卡
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        gainAbnormalSize = false;
                        WorkHourStatistics workHourStatistics = new WorkHourStatistics();
                        workHourStatistics.setUserid(userId);
                        getAbnormalClock(workHourStatistics);
                    }
                },300);
            }
        });
        swipeCardInfoLogistics_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }

    // 获取 项目分类 数据
    public List<String> projectType_list = new ArrayList<>();
    public void projectType(){
        projectType_list.clear();
        API.projectType(new IResponse() {
            @Override
            public void onSuccess(String response) throws IOException {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(response);
                        List<ProjectType> projectTypeList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectType>>(){}.getType());
                        Log.d(TAG, "-----项目类型----"+projectTypeList);
                        if (projectTypeList.size() > 0){
                            projectType_list.add("选择类型");
                            for (ProjectType type : projectTypeList) {
                                projectType_list.add(type.getTypename());
                            }
                        }
                        typeSpinner();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                Log.d(TAG, "onFail: -----刷新错误------:"+statusCode);
            }
        });
    }
    ArrayAdapter<String> typeSpinner_adapter;
    //  类型 spinner 实例化
    public void typeSpinner(){
        machineSpinnerBeanList.add(new MachineSpinnerBean("请选择机械部装", 0L));
        setAssemblyInfo();
        typeSpinner_adapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_item,projectType_list);
        sp_projectType.setAdapter(typeSpinner_adapter);
        sp_projectType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "----spinner选中类型----"+projectType_list.get(position));
                String str_spinner = projectType_list.get(position);
                mechanical_assembly_RB.setChecked(true);
                rg_electric_code.removeAllViews();
                clearList();
                if (str_spinner.equals("选择类型")) {
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择项目类型！！！");
                }else {
                    ProjectType projectType = new ProjectType();
                    projectType.setTypename(projectType_list.get(position));
                    //  设备 id
                    System.out.println("----设备 id----"+androidId);
                    projectType.setSerialnumber(androidId);
                    getStartProjectInfo(projectType);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    // 获取项目具体数据
    public void getStartProjectInfo(ProjectType projectType){
        API.getStartProjectInfo(projectType, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagementList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectManagement>>(){}.getType());
                        System.out.println("----123456789------"+projectManagementList);
                        projectnameList.clear();
                        String msg = j.getString("msg");
                        long l = Long.parseLong(j.getString("code"));
                        if (l == 200){
                            if (projectManagementList.size() > 0){
                                for (ProjectManagement p : projectManagementList) {
                                    projectnameList.add(new ProjectSpinner(p.getProjectname(),
                                            p.getProductacode(), p.getProjectid(),
                                            p.getDeptid() ,p.getElectricalBcode() ));
                                }
                            }else {
                                ToastUtils.warnShowLong(getApplicationContext(),"本设备下没有该类型的项目，请重新选择！");
                            }
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),msg);
                        }
                        setProject();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    String str_name, str_code, electricalCode;
    Long long_projectId, long_deptId;
    MyAdapter adapter;
    List<String> codeList = new ArrayList<>();
    //  项目数据渲染
    public void setProject(){
        codeList.clear();
        adapter = new MyAdapter(projectnameList, HomePageActivity.this);
        sp_projectName.setAdapter(adapter);
        sp_projectName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mechanical_assembly_RB.setChecked(true);
                Log.d(TAG, "---项目名称---"+projectnameList.get(position).getProjectName()+
                        "--项目code---"+projectnameList.get(position).getProjectACode()+
                        "---项目 id---"+projectnameList.get(position).getProjectId()+
                        "---部门id--"+projectnameList.get(position).getDeptId()+
                        "--电气编码---"+projectnameList.get(position).getElectrialCode() );

                str_name = projectnameList.get(position).getProjectName();
                str_code = projectnameList.get(position).getProjectACode();
                long_projectId = projectnameList.get(position).getProjectId();
                long_deptId = projectnameList.get(position).getDeptId();
                electricalCode = projectnameList.get(position).getElectrialCode();
                clearAssembly();
                codeList.clear();

                rg_electric_code.removeAllViews();
                if (electricalCode != null && !electricalCode.isEmpty()){
                    String[] parts = electricalCode.split("&");
                    for (String str : parts) {
                        Log.d("---提取到的内容----", str);
                        codeList.add(str);
                    }
                    if (long_projectId != null){
                        addRadioButton(long_projectId);
                    }else{
                        layout_electric_code.setVisibility(View.GONE);
                        spinnerBeanArrayList.add(new ElectricSpinnerBean("请选择电气部装", 0L));
                        setElectricSpinner();
                    }
                }else {
                    System.out.println("---电气编码为空----");
                    layout_electric_code.setVisibility(View.GONE);
                    spinnerBeanArrayList.add(new ElectricSpinnerBean("请选择电气部装", 0L));
                    setElectricSpinner();
                }

                tv_selectProject.setText(str_name+"( "+str_code+" )");

                getAssemblyInfo(long_projectId);   // 获取 部装信息
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });
    }

    private final ArrayList<MachineSpinnerBean> machineSpinnerBeanList = new ArrayList<>();  //  机械 部装

    public List<String> clockType_list = new ArrayList<>();

    public void selectAssemblyById(ProjectManagement p){
        machineSpinnerBeanList.clear();
        API.selectAssemblyById(p, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectInfoVo> projectInfoVoList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectInfoVo>>(){}.getType());
                        if (projectInfoVoList.size() > 0){
                            List<AssemblyManagement> assemblyList = projectInfoVoList.get(0).getAssemblyManagementList();
//                            List<ElectricalAssembly> electricalList = projectInfoVoList.get(0).getElectricalAssemblyList();
                            List<WorkClockType> workClockTypeList = projectInfoVoList.get(0).getWorkClockTypeList();

                            machineSpinnerBeanList.add(new MachineSpinnerBean("请选择机械部装", 0L));
                            if (assemblyList != null){
                                for (AssemblyManagement a : assemblyList) {
                                    machineSpinnerBeanList.add(new MachineSpinnerBean(a.getAssemblyname(),a.getAssemblyid()));
                                }
                            }
                            clockType_list.clear();
                            clockType_list.add("请选择类型");
                            if (workClockTypeList.size() > 0){
                                for (WorkClockType w : workClockTypeList) {
                                    clockType_list.add(w.getTypename());
                                }
                            }
                            Log.d(TAG, "run: ----打卡类型:----"+workClockTypeList);
                            setAssemblyInfo();
                        }
                    }
                });

            }
            @Override
            public void onFail(int statusCode) { }
        });
    }
    ElectricSpinnerAdapter electricName_adapter;
    MachineSpinnerAdapter machineSpinner_adapter;
    ArrayAdapter<String> clockType_adapter;
    Long machineAssemblyId = 0L, electricAssemblyId = 0L;
    public void setAssemblyInfo(){
        // 机械 部装
        machineSpinner_adapter = new MachineSpinnerAdapter(HomePageActivity.this,machineSpinnerBeanList);
        sp_machineAssembly.setAdapter(machineSpinner_adapter);
        sp_machineAssembly.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "机械部装id:----"+machineSpinnerBeanList.get(position).getMachineAssemblyId());
                machineAssemblyId = machineSpinnerBeanList.get(position).getMachineAssemblyId();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        clockType_adapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_item,clockType_list);
        sp_clockType.setAdapter(clockType_adapter);
    }

    //  部门 下拉框 数据
    public void findDeptByDu(){
        API.findDeptByDu(new IResponse() {
            @Override
            public void onSuccess(String response) throws IOException {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(response);
                        List<SysDept> sysDeptList = new Gson().fromJson(j.getString("data"), new TypeToken<List<SysDept>>(){}.getType());
                        System.out.println("---部门信息----"+sysDeptList);
                        customSpinnerBeanArrayList = new ArrayList<>();
                        if (sysDeptList.size() > 0){
                            for ( SysDept sysDept : sysDeptList) {
                                customSpinnerBeanArrayList.add( new CustomSpinnerBean(
                                        sysDept.getDeptName(),
                                        sysDept.getDeptId())
                                );
                            }
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    // 异常工时卡信息
    PopupWindow abnormal_pop;
    public void abnormalPop(List<WorkHourStatistics> w){
        View abnormal_view = getLayoutInflater().inflate(R.layout.abnormal_hour_tips,null);
        int width = ScreenUtils.getWidth(HomePageActivity.this);
        abnormal_pop = new PopupWindow
                (abnormal_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        abnormal_pop.setTouchable(true);
        abnormal_pop.setFocusable(false);
        abnormal_pop.setOutsideTouchable(false);
        Button yes_BT = abnormal_view.findViewById(R.id.yes_BT);
        Button no_BT = abnormal_view.findViewById(R.id.no_BT);
        TextView tv_abnormalTips = abnormal_view.findViewById(R.id.tv_abnormalTips);
        tv_abnormalTips.setText("您有 " + w.size() + " 条未处理的异常工单是否去处理！！！");
        yes_BT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                abnormal_pop.dismiss();
                String typeStr = w.get(0).getClocktype();
                Log.d(TAG, "-- 异常工单类型：---"+typeStr);
                switch (typeStr){
                    case "电气调试": case "机械调试":
                        Intent intent = new Intent(HomePageActivity.this,DebugLogActivity.class);
                        intent.putExtra("workhourid", w.get(0).getWorkhourid());
                        startActivity(intent);
                        break;
                    case "机械装配": case "电气装配":
                        Intent intent2 = new Intent(HomePageActivity.this,MainActivity.class);
                        intent2.putExtra("workhourid", w.get(0).getWorkhourid());
                        startActivity(intent2);
                        break;
                    case "打包":
                        Intent intent3 = new Intent(HomePageActivity.this,PackActivity.class);
                        intent3.putExtra("workhourid", w.get(0).getWorkhourid());
                        startActivity(intent3);
                        break;
                    default:
                        setAlpha(0.2f);
                        popAfterWorkAbnormal(w);
                        break;
                }
            }
        });
        no_BT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                abnormal_pop.dismiss();
            }
        });
        abnormal_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }

    String swipeTime_str;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.workOrder_IV:     // 工作日报
                // 定义变量以简化条件判断
                String groupText = group_TV.getText().toString();
                String clockTypeValue = clockType;   // 打卡类型

                // 检查是否已打卡 若没打上班卡则提示
                if (clockTypeValue == null) {
                    ToastUtils.warnShowLong(HomePageActivity.this, "请确认是否已经打下班卡");
                    return;
                }
                // 检查是否需要提示填报信息
                if ("生产后勤部".equals(groupText) || "车间整理".equals(clockTypeValue)) {
                    ToastUtils.warnShowLong(getApplicationContext(), "请在刷卡后的弹窗填报信息!!!");
                    return;
                }
                // 检查是否为调试类型
                if ("电气调试".equals(clockTypeValue) || "机械调试".equals(clockTypeValue)) {
                    ToastUtils.warnShowLong(HomePageActivity.this, "请前往调试日志上报信息");
                    return;
                }
                if ("机械装配".equals(clockTypeValue) || "电气装配".equals(clockTypeValue)){
                    swipeTime_str = swipeTime_TV.getText().toString();
                    Intent intent = new Intent(HomePageActivity.this, MainActivity.class);
                    intent.putExtra("workhourid", workhourid);
                    intent.putExtra("endTime", swipeTime_str);
                    intent.putExtra("deptId", user_deptid);
                    intent.putExtra("userId",userId);
                    launcher.launch(intent);
                }else {
                    ToastUtils.warnShowLong(HomePageActivity.this, "请刷卡后上报信息");
                    return;
                }

                break;
            case R.id.debugLog_IV:
                if (group_TV.getText().toString().equals("生产后勤部")){
                    ToastUtils.warnShowLong(getApplicationContext(),"请在刷卡后的弹窗填报信息!!!");
                }else {
                    if (clockType == null){
                        ToastUtils.warnShowLong(HomePageActivity.this,"请确认是否已经打下班卡");
                    }else if (clockType.equals("机械装配") || clockType.equals("车间整理") || clockType.equals("电气装配")){
                        ToastUtils.warnShowLong(HomePageActivity.this,"请前往日报填写模块上报信息");
                    }else {
                        swipeTime_str = swipeTime_TV.getText().toString();
                        Intent intent2 = new Intent(HomePageActivity.this,DebugLogActivity.class);
                        intent2.putExtra("userName",name_TV.getText().toString());
                        intent2.putExtra("group",group_TV.getText().toString());
                        intent2.putExtra("userId",userId);
                        intent2.putExtra("workhourid",workhourid);
                        intent2.putExtra("endTime",swipeTime_str);
                        launcher.launch(intent2);
                    }
                }
                break;
            case R.id.adminManager_IV:  // 其他 功能
                Intent intent1 = new Intent(HomePageActivity.this,AdminActivity.class);
                intent1.putExtra("userId",userId);
                startActivity(intent1);
                break;
            case R.id.downTime_layout:
                TimeSelect();
                break;
            case R.id.iv_notice:   // 异常信息
                gainAbnormalSize = false;
                WorkHourStatistics w = new WorkHourStatistics();
                w.setUserid(userId);
                getAbnormalClock(w);
                break;
            case R.id.layout_close:
                startActivity(new Intent(HomePageActivity.this,ScreensaverActivity.class));
                break;
            case R.id.iv_refresh:
                if (projectType_list.size() > 0) {
                    projectType_list.clear();
                }
                clearList();
                projectType();
                break;
            case R.id.iv_delect_punch:
                menuPopupwindow();
                break;
            case R.id.iv_home_refresh:
                reStartActivity();
                break;
            default:
                break;
        }
    }
    public void setPunchStatus (){
        WorkHourStatistics w = new WorkHourStatistics();
        w.setUserid(userId);
        w.setProducedate(TimeUtils.getCurrentDate());
        w.setStatus("上班中");
        if (userId == null){
            ToastUtils.warnShowLong(HomePageActivity.this,"请先刷卡");
        }else {
            punchStatus(w);
        }
    }
    PopupWindow punchStatus_pop;
    View delect_view;
    public void punchStatusPop (){
        delect_view = getLayoutInflater().inflate(R.layout.delect_work_order_pop,null);
        int width = ScreenUtils.getWidth(HomePageActivity.this);
        punchStatus_pop = new PopupWindow
                (delect_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        punchStatus_pop.setTouchable(true);
        punchStatus_pop.setFocusable(true);
        punchStatus_pop.setOutsideTouchable(true);
        punchStatus_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
        setpunchStatusPop();
    }
    TextView de_punch_code, de_punch_project, de_punch_type, de_punch_time, de_punch_staff, tv_tip;
    Button bt_delect, bt_cancel;
    public void setpunchStatusPop(){
        de_punch_project = delect_view.findViewById(R.id.de_punch_project);
        de_punch_code = delect_view.findViewById(R.id.de_punch_code);
        de_punch_type = delect_view.findViewById(R.id.de_punch_type);
        de_punch_time = delect_view.findViewById(R.id.de_punch_time);
        de_punch_staff = delect_view.findViewById(R.id.de_punch_staff);
        bt_delect = delect_view.findViewById(R.id.bt_delect);
        tv_tip = delect_view.findViewById(R.id.tv_tip);
        bt_delect.setOnClickListener(this);
        bt_cancel = delect_view.findViewById(R.id.bt_cancel);
        setPunchStatus ();
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                punchStatus_pop.dismiss();
            }
        });
        bt_delect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inquireDialog();
            }
        });
    }

    Long delect_workId;
    String de_clockType, de_starttime, de_nickname, punch_project_str , punch_code_str;
    public void clearDelectInfo (){
        delect_workId = null;
        de_clockType = null;
        de_starttime = null;
        de_nickname = null;
        punch_project_str = null;
        punch_code_str = null;
    }
    //  判断今日打卡
    public void punchStatus (WorkHourStatistics w){
        clearDelectInfo();
        API.clockInStatus(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        List<WorkHourStatistics> workHourList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType());
                        Log.d(TAG, "----删除的工单信息-----"+workHourList);
                        if (workHourList.size() > 0 ){
                            if (workHourList.size() == 1){
                                de_clockType = workHourList.get(0).getClocktype();
                                delect_workId = workHourList.get(0).getWorkhourid();
                                de_starttime = workHourList.get(0).getStarttime();
                                de_nickname = workHourList.get(0).getNickName();
                                punch_project_str = workHourList.get(0).getProjectName();
                                punch_code_str = workHourList.get(0).getProductAcode();
                                de_punch_project.setText(punch_project_str);
                                de_punch_code.setText(punch_code_str);
                               if (de_punch_project.getText().toString().equals("")){
                                   de_punch_project.setText("无");
                               }
                               if (de_punch_code.getText().toString().equals("")){
                                   de_punch_code.setText("无");
                               }
                                de_punch_type.setText(de_clockType);
                                de_punch_time.setText(de_starttime);
                                de_punch_staff.setText(de_nickname);

                                if (TimeUtils.setTime(de_starttime,TimeUtils.getCurrentDateTime()) > 5 ){
                                    tv_tip.setVisibility(View.VISIBLE);
                                    bt_delect.setVisibility(View.GONE);
                                }else {
                                    tv_tip.setVisibility(View.GONE);
                                    bt_delect.setVisibility(View.VISIBLE);
                                }
                            }else {
                                ToastUtils.warnShowLong(HomePageActivity.this,"今日存多条《上班中》记录，请联系管理员");
                                if (punchStatus_pop != null){
                                    punchStatus_pop.dismiss();
                                }
                            }
                        }else {
                            ToastUtils.warnShowLong(HomePageActivity.this,"今日暂无打卡记录");
                            if (punchStatus_pop != null){
                                punchStatus_pop.dismiss();
                            }
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    public void delectWorkHour(WorkHourStatistics w){
        API.delectWorkHour(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onSuccess: ------ 删除 ----");
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        long l = Long.parseLong(jsonObject.getString("code"));
                        if (l == 200){
                            ToastUtils.successShowLong(HomePageActivity.this,"删除成功！");
                            if (punchStatus_pop != null){
                                punchStatus_pop.dismiss();
                            }
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),"删除失败，请联系管理员！！！");
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

//    询问弹窗
    public void inquireDialog(){
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("  删 除 提 醒 ！ ！ ！")
                .setMessage("确定《 删除 》这条打卡数据吗？")
                .setIcon(R.mipmap.jinggao2)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        WorkHourStatistics w = new WorkHourStatistics();
                        if (delect_workId != null){
                            w.setWorkhourid(delect_workId);
                            delectWorkHour(w);
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),"请确认是否已经打卡！！！");
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ToastUtils.successShowLong(getApplicationContext(),"已取消");
                    }
                })
                .create();
        alertDialog.show();
    }
    //   打包 跳转
    String str_swipe_time;
    public void punchInDialog (String clockType){
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("  跳 转 提 醒 ！ ！ ！")
                .setMessage("是否跳转到《"+ clockType +"上报 》界面？")
                .setIcon(R.mipmap.xunwen)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        str_swipe_time = swipeTime_TV.getText().toString();
                        Intent intent = new Intent(HomePageActivity.this,PackActivity.class);
                        intent.putExtra("workhourid", workhourid);
                        intent.putExtra("endTime", str_swipe_time);
                        intent.putExtra("deptId", user_deptid);
                        intent.putExtra("userId",userId);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ToastUtils.successShowLong(getApplicationContext(),"已取消");
                    }
                })
                .create();
        alertDialog.show();
    }

    private void reStartActivity() {       // 刷新 当前Activity
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
    public void setAdminIDcard(){
        SysUser sysUser = new SysUser();
        sysUser.setUserId(1L);
        seleceStaffInfo(sysUser);
    }
    //  清空 列表
    public void clearList() {
        if (projectnameList.size() > 0){
            projectnameList.clear();
            tv_selectProject.setText("null");
            str_name = null;
            str_code = null;
            long_projectId = null;
            long_deptId = null;
            machineAssemblyId = null;
            electricAssemblyId = null;
            adapter = new MyAdapter(projectnameList, HomePageActivity.this);
            sp_projectName.setAdapter(adapter);
        }
        if (machineSpinnerBeanList.size() > 0){
            machineSpinnerBeanList.clear();
        }
        if (spinnerBeanArrayList.size() > 0){
            spinnerBeanArrayList.clear();
        }
        if (clockType_list.size() > 0){
            clockType_list.clear();
        }
        setAssemblyInfo();
    }
    public void clearAssembly() {
        machineAssemblyId = null;
        electricAssemblyId = null;
        if (machineSpinnerBeanList.size() > 0){
            machineSpinnerBeanList.clear();
        }
        if (spinnerBeanArrayList.size() > 0){
            spinnerBeanArrayList.clear();
        }
        if (clockType_list.size() > 0){
            clockType_list.clear();
        }
        setAssemblyInfo();

    }

    //  查询 异常工单
    public void getAbnormalClock(WorkHourStatistics w){
        API.getAbnormalClock(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<WorkHourStatistics> w = new Gson().fromJson(j.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType() );
                        System.out.println("--- 异常 工单  ----"+j);
                        if (w != null && w.size() > 0){
                            iv_notice.setVisibility(View.VISIBLE);
//                            badgeView.setBadgeNumber(w.size());  // 设置角标数量
                            badgeView.setBadgeText("");
                            badgeView.setShowShadow(false);     // 去除阴影
                            badgeView.setBadgeGravity(Gravity.END | Gravity.TOP);
                            if (!gainAbnormalSize){
                                abnormalPop(w);     //  打开 异常 提醒
                            }
                        }else {
                            iv_notice.setVisibility(View.GONE);
                            badgeView.hide(true);  // 隐藏角标
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    // 上班 打卡
    public void workClockIn(WorkHourStatistics workHourStatistics){
        API.workClockIn(workHourStatistics, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        Log.d(TAG, "--上班....--"+jsonObject);
                        long l = Long.parseLong(jsonObject.getString("code"));
                        if (l == 200){
                            System.out.println(jsonObject+"--上班打卡完成---"+jsonObject.getString("msg"));
                            ToastUtils.successShowLong(getApplicationContext(),"打卡成功！");
                            startAuto("打卡成功");
                            if (swipeCardInfoLogistics_pop != null){
                                swipeCardInfoLogistics_pop.dismiss();  // 生产打卡
                            }
                            if (swipeCardInfo_pop != null){
                                swipeCardInfo_pop.dismiss();
                            }
                            setAbnormalClock();
                        }else {
                            ToastUtils.warnShowLong(HomePageActivity.this,"请勿重复打卡！！！");
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                Log.d(TAG, "onFail: --错误信息---"+statusCode);
            }
        });
    }
    public List<String> staff_list = new ArrayList<>();
    Boolean gainAbnormalSize = false;
    // 员工 信息
    public void seleceStaffInfo(SysUser sysUser){
        API.seleceStaffInfo(sysUser, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                List<SysUser> sysUserList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<SysUser>>(){}.getType());
                System.out.println("---0000000-----"+sysUserList);
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (sysUserList.size() == 0){
                            name_TV.setText("");
                            group_TV.setText("");
                            ToastUtils.warnShowLong(getApplicationContext(),"此卡为空卡，请联系管理员添加");
                            startAuto("此卡为空卡，请联系管理员添加");
                        }else {
                            if (sysUserList.size() == 1){
                                if (sysUserList.get(0).getUserId() == 1){
                                    Log.d(TAG, "刷卡信息------"+sysUserList.get(0).getIcCard());
                                    idCard = sysUserList.get(0).getIcCard();
                                }else {
                                    name_TV.setText(sysUserList.get(0).getNickName());
                                    String group_str = sysUserList.get(0).getDept().getDeptName();
                                    group_TV.setText(group_str);
                                    cardNumber_ET.setText(sysUserList.get(0).getIcCard());
                                    userId = sysUserList.get(0).getUserId();
                                    user_deptid = sysUserList.get(0).getDept().getDeptId();    // 员工下的部门

                                    System.out.println("-- 部门id---"+sysUserList.get(0).getDeptId()+"*****"+user_deptid);
                                    swipeTime_TV.setText(TimeUtils.getCurrentDateTime());
                                    //  查询异常工单
                                    WorkHourStatistics workHourStatistics = new WorkHourStatistics();
                                    workHourStatistics.setUserid(userId);
                                    getAbnormalClock(workHourStatistics);
                                    gainAbnormalSize = true;

                                    if (!name_TV.getText().toString().equals("")){
                                        startAuto("刷卡成功"+name_TV.getText().toString());
                                        // 需要判断是否是上下班
                                        WorkHourStatistics w = new WorkHourStatistics();
                                        w.setUserid(userId);
                                        w.setProducedate(TimeUtils.getCurrentDate());
                                        w.setStatus("上班中");
                                        clockType = null;
                                        clockInStatus(w,group_str);  //查看上班状态
                                    }
                                }
                            }else {
                                for (SysUser sysUser : sysUserList) {
                                    staff_list.add(sysUser.getNickName());
                                }
                            }
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    Long workhourid ;
    // 判断上下班
    public void clockInStatus(WorkHourStatistics workHourStatistics,String str){
        starttime = ""; nickName = "";  deptName="";
        API.clockInStatus(workHourStatistics, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        List<WorkHourStatistics> workHourList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType());
                        if (workHourList.size() == 0){
                            if (is){
                                staff_pop.dismiss();
                                is = false;
                            }
                            if (!str.equals("生产后勤部")){
                                //  员工打卡界面
                                popSwipeCardInfo();
                                setAlpha(0.2f);
                                swipeCardInfo_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                                    @Override
                                    public void onDismiss() {
                                        setAlpha(1.0f);
                                    }
                                });
                            }else {       //  后勤打卡 弹窗
                                popSwipeCardInfoLogistics();
                                setAlpha(0.2f);
                            }
                        }else {
                            // 第二次 刷卡   下班
                            System.out.println("---记录工时信息 -------"+workHourList.get(0).getClocktype());
                            clockType = workHourList.get(0).getClocktype().trim();   // 获取内容 并 去除头尾空字符
                            workhourid = workHourList.get(0).getWorkhourid();
                            starttime = workHourList.get(0).getStarttime();
                            nickName = workHourList.get(0).getNickName();
                            deptName = workHourList.get(0).getDeptName();

                            if (clockType.equals("机械装配") || clockType.equals("电气装配") ||
                                 clockType.equals("电气调试") || clockType.equals("机械调试")  ){
                                ToastUtils.successShowLong(HomePageActivity.this,"刷卡成功");
                                startAuto("下班刷卡成功"+workHourList.get(0).getNickName()+"记得填报"+clockType+"信息");
                            }else {
                                Log.d(TAG, "--- 其他工作-----");
                                startAuto("刷卡成功，请确认下班！！！");
                                if (clockType.trim().equals("打包") || clockType.trim().equals("装车发货")){
                                    punchInDialog(clockType);
                                }else {
                                    WorkHourStatistics w = new WorkHourStatistics();
                                    w.setStarttime(starttime);
                                    w.setUserid(userId);
                                    w.setEndtime(swipeTime_TV.getText().toString());
                                    calculateDuration(w);

                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (duration == null || duration.equals("")){
                                                ToastUtils.warnShowLong(HomePageActivity.this,"下班时长获取失败，请重新打卡");
                                            }else {
                                                popAfterWork();
                                                setAlpha(0.3f);
                                            }
                                        }
                                    },666);
                                }
                            }
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    //  根据开始 + 结束 + useid 查询工时
    public void calculateDuration(WorkHourStatistics w){
        duration = "";
        API.calculateDuration(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        System.out.println("----- 实际工时-------"+result);
                        duration = jsonObject.getString("msg");
                        if (durationType){
                            tv_durationFill.setText(duration);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    //  下班打卡 弹窗
    PopupWindow afterWork_pop;
    public void popAfterWork(){
        View afterWork_view = getLayoutInflater().inflate(R.layout.after_work_pop,null);
        TextView tv_AWname = afterWork_view.findViewById(R.id.tv_AWname);
        TextView tv_AWdept = afterWork_view.findViewById(R.id.tv_AWdept);
        TextView tv_starttime = afterWork_view.findViewById(R.id.tv_starttime);
        TextView tv_endTime = afterWork_view.findViewById(R.id.tv_endTime);
        TextView tv_duration = afterWork_view.findViewById(R.id.tv_duration);
        TextView tv_clockType = afterWork_view.findViewById(R.id.tv_clockType);
        EditText et_JobContent = afterWork_view.findViewById(R.id.et_JobContent);
        EditText et_suggest = afterWork_view.findViewById(R.id.et_suggest);
        Button bt_afterWork = afterWork_view.findViewById(R.id.bt_afterWork);
        ImageView iv_close = afterWork_view.findViewById(R.id.iv_close);
        LinearLayout layout_borrow = afterWork_view.findViewById(R.id.layout_borrow);
        EditText et_borrow_direction = afterWork_view.findViewById(R.id.et_borrow_direction);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                afterWork_pop.dismiss();
                clearPopAfterWork();
            }
        });
        tv_AWname.setText(nickName);
        tv_AWdept.setText(deptName);
        tv_starttime.setText(starttime);
        tv_endTime.setText(swipeTime_TV.getText().toString());
        tv_duration.setText(duration);
        tv_clockType.setText(clockType);
        if (clockType.replace(" ", "").equals("人员借用")){
            layout_borrow.setVisibility(View.VISIBLE);
        }else {
            layout_borrow.setVisibility(View.GONE);
        }
        bt_afterWork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NoDoubleClickUtil.isFastDoubleClick()){return;}
                String str_jobContent = et_JobContent.getText().toString();
                String str_suggest = et_suggest.getText().toString();
                String str_borrow_direction = et_borrow_direction.getText().toString();
                String clockTypeTrimmed = clockType.trim();
                if (clockTypeTrimmed.equals("人员借用") && str_borrow_direction.isEmpty()) {
                    ToastUtils.warnShowLong(getApplicationContext(), "请确保 < 借用去向 > 不为空！");
                    return;
                }
                if (str_jobContent.isEmpty()) {
                    ToastUtils.warnShowLong(getApplicationContext(), "请确保 < 工作内容 > 不为空！！");
                    return;
                }
                popClose = false;
                WorkHourStatistics w = new WorkHourStatistics();
                w.setBelowSerialNo(androidId);
                w.setWorkhourid(workhourid);
                w.setEndtime(swipeTime_TV.getText().toString());
                w.setDuration(duration);
                if (str_borrow_direction.isEmpty()){
                    w.setWorkDetails(str_jobContent);
                }else {
                    w.setWorkDetails("《 去向明细："+str_borrow_direction+" 》 "+str_jobContent);
                }
                w.setRationalizationProposal(str_suggest);
                updateWorkOrder(w);
            }
        });
        int width = ScreenUtils.getWidth(getApplicationContext());
        afterWork_pop = new PopupWindow
                (afterWork_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        afterWork_pop.setTouchable(true);
        afterWork_pop.setFocusable(true);
        afterWork_pop.setOutsideTouchable(true);
        afterWork_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1.0f);
            }
        });
        afterWork_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }
    public void clearPopAfterWork (){
        nickName = "";
        deptName = "";
        starttime = "";
        duration = "";
        clockType = "";
    }


    //  生产后勤 异常工单
    PopupWindow afterWorkAbnormal_pop;
    public void popAfterWorkAbnormal(List<WorkHourStatistics> workHourStatisticsList){
        View afterWorkAbnormal_view = getLayoutInflater().inflate(R.layout.after_work_pop_abnormal,null);
        TextView tv_AWFillname = afterWorkAbnormal_view.findViewById(R.id.tv_AWFillname);
        TextView tv_AWFilldept = afterWorkAbnormal_view.findViewById(R.id.tv_AWFilldept);
        TextView tv_fillClockType = afterWorkAbnormal_view.findViewById(R.id.tv_fillClockType);  //  补卡类型
        tv_fillClockType.setText(workHourStatisticsList.get(0).getClocktype());
        tv_starttimeFill = afterWorkAbnormal_view.findViewById(R.id.tv_starttimeFill);
        tv_durationFill = afterWorkAbnormal_view.findViewById(R.id.tv_durationFill);
        EditText et_JobContentFill = afterWorkAbnormal_view.findViewById(R.id.et_JobContentFill);
        EditText et_suggest_abnormal = afterWorkAbnormal_view.findViewById(R.id.et_suggest_abnormal);
        Button bt_afterWorkFill = afterWorkAbnormal_view.findViewById(R.id.bt_afterWorkFill);
        ImageView iv_close = afterWorkAbnormal_view.findViewById(R.id.iv_close);
        downTime_layout =  afterWorkAbnormal_view.findViewById(R.id.downTime_layout);
        downTime_layout.setOnClickListener(this);
        downTime_TV = afterWorkAbnormal_view.findViewById(R.id.downTime_TV);
        fill_userID = workHourStatisticsList.get(0).getUserid();
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                afterWorkAbnormal_pop.dismiss();
                setAlpha(1.0f);
            }
        });
        tv_AWFillname.setText(name_TV.getText().toString());
        tv_AWFilldept.setText(workHourStatisticsList.get(0).getDeptName());
        tv_starttimeFill.setText(workHourStatisticsList.get(0).getStarttime());
        bt_afterWorkFill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NoDoubleClickUtil.isFastDoubleClick()){return;}
                String str_jobContentFill = et_JobContentFill.getText().toString();
                String str_suggest_abnormal = et_suggest_abnormal.getText().toString();
                if (str_jobContentFill.isEmpty()){
                    ToastUtils.warnShowLong(getApplicationContext(),"请确保工作内容不为空！！");
                }else {
                    WorkHourStatistics w = new WorkHourStatistics();
                    String str_downTime = downTime_TV.getText().toString();
                    String str_durationFill = tv_durationFill.getText().toString();
                    if (str_durationFill.length() > 0){
                        w.setWorkhourid(workHourStatisticsList.get(0).getWorkhourid());
                        w.setEndtime(str_downTime);
                        w.setDuration(str_durationFill);
                        w.setWorkDetails(str_jobContentFill);
                        w.setBelowSerialNo(androidId);
                        w.setRationalizationProposal(str_suggest_abnormal);
                        updateWorkOrder(w);
                        popClose = true;
                    }else {
                        ToastUtils.warnShowLong(getApplicationContext(),"请选择下工时间！！！");
                    }
                }
            }
        });
        int width = ScreenUtils.getWidth(getApplicationContext());
        afterWorkAbnormal_pop = new PopupWindow
                (afterWorkAbnormal_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        afterWorkAbnormal_pop.setTouchable(true);
        afterWorkAbnormal_pop.setFocusable(true);
        afterWorkAbnormal_pop.setOutsideTouchable(true);
        afterWorkAbnormal_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1.0f);
            }
        });
        afterWorkAbnormal_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }

    //  生产后勤 工单修改
    public void updateWorkOrder(WorkHourStatistics w){
        API.updateWorkOrder(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String msg = j.getString("msg");
                        if (msg.equals("操作成功")){
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (popClose){
                                        if (afterWorkAbnormal_pop != null){
                                            afterWorkAbnormal_pop.dismiss();
                                        }
                                        startAuto("异常工单补卡成功！！！");
                                        ToastUtils.successShowLong(getApplicationContext(),"异常工单补卡成功！！！");
                                    }else {
                                        if (afterWork_pop != null){
                                            afterWork_pop.dismiss();
                                        }
                                        startAuto("下班打卡成功！！！");
                                        ToastUtils.successShowLong(getApplicationContext(),"下班打卡成功！！");
                                    }
                                }
                            },300);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    StringBuilder sb = new StringBuilder();
    // 时间 选择器 自定义
    public void TimeSelect (){
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);  // 小时
        int minute = calendar.get(Calendar.MINUTE);     // 分钟
        new TimePickerDialog(HomePageActivity.this, AlertDialog.THEME_HOLO_LIGHT,new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                tv_durationFill.setText("");    // 清空 工作时长
                sb.setLength(0);                // 清空 StringBuilder
                String formattedTime = formatTime(hourOfDay, minute);
                System.out.println("---  时间 ---" + formattedTime);
                SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                // 解析日期时间字符串
                Date dateTimeObj = null;
                try {
                    dateTimeObj = dateTimeFormat.parse(tv_starttimeFill.getText().toString());
                    // 提取日期部分并格式化为字符串
                    String dateStr = dateFormat.format(dateTimeObj);
                    System.out.println(dateStr);
                    sb.append(dateStr).append(" ").append(formattedTime).append(":00");
                    boolean  i = getTimeCompareSize(tv_starttimeFill.getText().toString(),sb.toString());
                    System.out.println(i+"----- 时间比较 -----");
                    if (!i){
                        durationType = true;
                        downTime_TV.setText(sb);
                        WorkHourStatistics w = new WorkHourStatistics();
                        w.setStarttime(tv_starttimeFill.getText().toString());
                        w.setUserid(fill_userID);
                        w.setEndtime(downTime_TV.getText().toString());
                        calculateDuration(w);
                    }else {
                        ToastUtils.warnShowLong(getApplicationContext(),"选择时间小于开始时间，请重新选择!!");
                        downTime_TV.setText("请重新选择");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        },hour,minute,true).show();
    }
    // 时间 格式转化
    private String formatTime(int hourOfDay, int minute) {
        // 使用String.format来格式化时间
        return String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
    }

    // 语音
    private void initTTS() {
        //实例化自带语音对象
        textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == textToSpeech.SUCCESS) {
                    textToSpeech.setPitch(1.0f);//方法用来控制音调
                    textToSpeech.setSpeechRate(2.0f);//用来控制语速
                    //判断是否支持下面两种语言
                    int result1 = textToSpeech.setLanguage(Locale.US);
                    int result2 = textToSpeech.setLanguage(Locale.
                            SIMPLIFIED_CHINESE);
                    boolean a = (result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED);
                    boolean b = (result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED);
                    Log.i("zhh_tts", "US支持否？--》" + a +
                            "\nzh-CN支持否》--》" + b);
                } else {
                    ToastUtils.warnShowLong(getApplicationContext(),"数据丢失或不支持");
                }
            }
        });
    }
    private void startAuto(String data) {
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        textToSpeech.setPitch(1.0f);
        // 设置语速
        textToSpeech.setSpeechRate(1.0f);
        textToSpeech.speak(data,             //输入中文，若不支持的设备则不会读出来
                TextToSpeech.QUEUE_FLUSH, null);  // 有新任务时关闭语言，执行新的
    }
//  activity 获取焦点时调用，解决语音返回桌面再次进入语音失效问题
    @Override
    protected void onResume() {
        super.onResume();
        initTTS();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (textToSpeech != null){
            textToSpeech.stop(); // 不管是否正在朗读TTS都被打断
            textToSpeech.shutdown(); // 关闭，释放资源
        }
//        stopService(serviceIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
    // 点击键盘外 关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
    //主动关闭软键盘
    public void hintKeyBoard (){
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
    public void CloseInput(EditText editText){
        //  设置 edittext有光标但不弹出软键盘
        if (android.os.Build.VERSION.SDK_INT > 10){   //4.0以上
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(editText, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //    弹窗 遮罩层
    private void setAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    // 设置 按两次返回键 退出app
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                ToastUtils.warnShowLong(getApplicationContext(),"再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                // 退出 销毁
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 对比两个时间
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static boolean getTimeCompareSize(String startTime, String endTime) {
        int i = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime() < date1.getTime()) {
                i = 1;
            } else if (date2.getTime() == date1.getTime()) {
                i = 2;
            } else if (date2.getTime() > date1.getTime()) {
                //正常情况下的逻辑操作.
                i = 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (i == 1 || i == 2) {
            return true;
        } else {
            return false;
        }
    }
    PopupWindow menu_pop;
    //  目录 弹窗
    public void menuPopupwindow(){
        // 设置布局文件
        menu_pop.setContentView(LayoutInflater.from(this).inflate(R.layout.menu_pop, null));
        menu_pop.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        menu_pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        menu_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
        menu_pop.setFocusable(true);
        menu_pop.setTouchable(true);
        menu_pop.setOutsideTouchable(true);
        menu_pop.showAsDropDown(iv_delect_punch, 20, 0);
        menu_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {}
        });
        TextView tv_delect = menu_pop.getContentView().findViewById(R.id.tv_delect);
        tv_delect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   // 删除
                menu_pop.dismiss();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        punchStatusPop ();
                    }
                },300);
            }
        });
        TextView tv_edit = menu_pop.getContentView().findViewById(R.id.tv_edit);
        tv_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   // 编辑
                menu_pop.dismiss();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setEditPop();
                    }
                },300);

            }
        });
        TextView tv_bind_device = menu_pop.getContentView().findViewById(R.id.tv_bind_device);
        tv_bind_device.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {   // 绑定设备
                menu_pop.dismiss();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("点击----- 绑定设备");
                        FactoryDeviceManagement f = new FactoryDeviceManagement();
                        f.setSerialnumber(androidId);
                        setDeviceNumber(f);
                    }
                },300);
            }
        });
    }
    //  编辑 弹窗
    PopupWindow edit_pop;
    View edit_view;
    public void setEditPop (){
        edit_view = getLayoutInflater().inflate(R.layout.edit_tip_pop,null);
        int width = ScreenUtils.getWidth(HomePageActivity.this);
        edit_pop = new PopupWindow
                (edit_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        edit_pop.setTouchable(true);
        edit_pop.setFocusable(true);
        edit_pop.setOutsideTouchable(true);
        edit_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
        setEditView();
    }
    TextView tv_edit_tip, tv_edit_info;
    Button bt_edit, bt_edit_cancel;
    public void setEditView (){
        tv_edit_info = edit_view.findViewById(R.id.tv_edit_info);
        tv_edit_tip = edit_view.findViewById(R.id.tv_edit_tip);
        bt_edit = edit_view.findViewById(R.id.bt_edit);
        bt_edit_cancel = edit_view.findViewById(R.id.bt_edit_cancel);
        setLatestWorkOrder();
        bt_edit_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_pop.dismiss();
            }
        });
    }
    public void setEditClose(){
        if (edit_pop != null){
            edit_pop.dismiss();
        }
    }
    public void setBtEdit (List<WorkHourStatistics> workHourList){
        edit_type = workHourList.get(0).getClocktype();
        Long edit_work_id = workHourList.get(0).getWorkhourid();
        bt_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setEditClose();
                switch (edit_type){
                    case "机械装配":
                    case "电气装配":
                        Intent intent = new Intent(HomePageActivity.this, EditAssembleActivity.class);
                        intent.putExtra("editWorkId", edit_work_id);
                        launcher.launch(intent);
                        break;
                    case "机械调试":
                    case "电气调试":
                        Intent intent2 = new Intent(HomePageActivity.this, EditDebugActivity.class);
                        intent2.putExtra("editWorkId", edit_work_id);
                        launcher.launch(intent2);
                        break;
                    default:
                        editPop(workHourList);
                        break;
                }
            }
        });
    }
    //  其他工作 修改弹窗
    PopupWindow edit_other_work_pop;
    View edit_other_work_view;
    public void editPop (List<WorkHourStatistics> workHourList){
        edit_other_work_view = getLayoutInflater().inflate(R.layout.edit_other_work,null);
        int width = ScreenUtils.getWidth(getApplicationContext());
        edit_other_work_pop = new PopupWindow
                (edit_other_work_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        edit_other_work_pop.setTouchable(true);
        edit_other_work_pop.setFocusable(true);
        edit_other_work_pop.setOutsideTouchable(true);
        edit_other_work_pop.showAtLocation(HomePageActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);

        TextView tv_name = edit_other_work_view.findViewById(R.id.tv_name);
        TextView tv_start_time = edit_other_work_view.findViewById(R.id.tv_start_time);
        TextView tv_end_time = edit_other_work_view.findViewById(R.id.tv_end_time);
        TextView tv_duration = edit_other_work_view.findViewById(R.id.tv_duration);
        TextView tv_clock_type = edit_other_work_view.findViewById(R.id.tv_clock_type);
        EditText et_job_content = edit_other_work_view.findViewById(R.id.et_job_content);
        Button bt_edit = edit_other_work_view.findViewById(R.id.bt_edit);
        ImageView iv_close = edit_other_work_view.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_other_work_pop.dismiss();
            }
        });
        tv_name.setText(workHourList.get(0).getNickName());
        tv_start_time.setText(workHourList.get(0).getStarttime());
        tv_end_time.setText(workHourList.get(0).getEndtime());
        tv_duration.setText(workHourList.get(0).getDuration());
        tv_clock_type.setText(workHourList.get(0).getClocktype());
        et_job_content.setText(workHourList.get(0).getWorkDetails());

        bt_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str_content = et_job_content.getText().toString();
                if (str_content.equals("")){
                    ToastUtils.warnShowLong(getApplicationContext(),"工作内容不为空！");
                }else {
                    WorkHourStatistics w = new WorkHourStatistics();
                    w.setWorkhourid(workHourList.get(0).getWorkhourid());
                    w.setWorkDetails(str_content);
                    editWorkHours(w);
                }
            }
        });
    }
    //  修改 工单
    public void editWorkHours(WorkHourStatistics w){
        API.editWorkHour(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        long l = Long.parseLong(j.getString("code"));
                        if (l == 200){
                            ToastUtils.successShowLong(getApplicationContext(),"工单修改成功！");
                            if (edit_other_work_pop != null){
                                edit_other_work_pop.dismiss();
                            }
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),"工单修改失败！");
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    public void setLatestWorkOrder (){
        WorkHourStatistics w = new WorkHourStatistics();
        w.setUserid(userId);
        w.setProducedate(TimeUtils.getCurrentDate());
        w.setStatus("已下班");
        if (userId == null){
            tv_edit_tip.setVisibility(View.GONE);
            bt_edit.setVisibility(View.GONE);
            tv_edit_info.setText("  请先刷卡！  ");
        }else {
            bt_edit.setVisibility(View.VISIBLE);
            bt_edit_cancel.setVisibility(View.VISIBLE);
            getLatestWorkOrder(w);
        }
    }
    Long edit_work_ID;
    String edit_type;
    public void getLatestWorkOrder (WorkHourStatistics w){
        edit_work_ID = null;  edit_type = null;
        API.getLatestWorkOrder(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        List<WorkHourStatistics> workHourList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType());
                        Log.d(TAG, "----最新 工单信息-----"+workHourList);
                        if (workHourList.size() > 0){
                            String endTime_str = workHourList.get(0).getEndtime();
                            if (TimeUtils.setTime(endTime_str, TimeUtils.getCurrentDateTime()) < 10 ){
                                Log.d(TAG, "---在规定时间内---"+endTime_str);
                                tv_edit_tip.setVisibility(View.GONE);
                                tv_edit_info.setVisibility(View.VISIBLE);
                                bt_edit.setVisibility(View.VISIBLE);

                                setBtEdit(workHourList);
                            }else {
                                Log.d(TAG, "---时间超出----");
                                tv_edit_tip.setVisibility(View.VISIBLE);
                                bt_edit.setVisibility(View.GONE);
                            }
                        }else {
                            Log.d(TAG, "---今日无下班的工单---");
                            bt_edit.setVisibility(View.GONE);
                            bt_edit_cancel.setVisibility(View.VISIBLE);
                            tv_edit_tip.setVisibility(View.GONE);
                            tv_edit_info.setVisibility(View.VISIBLE);
                            tv_edit_info.setText("   今日暂无完成工单，无法进行修改！！！");
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) { }
        });
    }

    //   动态 添加 RadioButton
    RadioButton rb_craft;
    @SuppressLint({"ResourceType", "UseCompatLoadingForColorStateLists"})
    public void addRadioButton(Long project_id){
        for (String s : codeList) {
            rb_craft = new RadioButton(HomePageActivity.this);
            // 设置 RadioButton 的大小和边距
            RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
            lp.height = dpToPx(35);
            lp.setMargins(dpToPx(10), dpToPx(15), dpToPx(10), 0);
            rb_craft.setLayoutParams(lp);
            rb_craft.setText( s );
            rb_craft.setPadding(dpToPx(10),0 ,dpToPx(10),0);
            rb_craft.setButtonDrawable(null);

            rb_craft.setGravity(Gravity.CENTER);
            rb_craft.setBackgroundResource(R.drawable.selector_speed_borrow_select_day);
            rb_craft.setTextColor(getResources().getColorStateList(R.drawable.selector_select_day));
            rb_craft.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
            rg_electric_code.addView(rb_craft);
        }
        spinnerBeanArrayList.add(new ElectricSpinnerBean("请选择电气部装", 0L));
        setElectricSpinner();
        rg_electric_code.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                String str_electricalCode = radioButton.getText().toString();
                System.out.println("---选中 b 码--"+str_electricalCode);
                tv_selectProject.setText(str_name+"( "+str_code+" - "+ str_electricalCode +" )");
                //
                ElectricalProcess e = new ElectricalProcess();
                e.setElectricalBcode(str_electricalCode);
                e.setProjectid(project_id);
                getElectricalProcess(e);
            }
        });

    }
    
    private final ArrayList<ElectricSpinnerBean> spinnerBeanArrayList = new ArrayList<>();   // 电气列表
    public void getElectricalProcess (ElectricalProcess process){
        spinnerBeanArrayList.clear();
        API.getElectricalProcess(process, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                HomePageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ElectricalProcess> electricalProcessList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ElectricalProcess>>(){}.getType());
                        System.out.println("---部装信息---"+electricalProcessList);
                        spinnerBeanArrayList.add(new ElectricSpinnerBean("请选择电气部装", 0L));
                        if (electricalProcessList.size() > 0){
                            for (ElectricalProcess e : electricalProcessList) {
                                spinnerBeanArrayList.add(new ElectricSpinnerBean(e.getProcessname(),e.getElectricalassemblyid() ));
                            }
                            System.out.println("=========="+spinnerBeanArrayList);
                        }
                        setElectricSpinner();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 电气 部装
    public void setElectricSpinner (){
        electricName_adapter = new ElectricSpinnerAdapter(spinnerBeanArrayList,HomePageActivity.this);
        sp_electricAssembly.setAdapter(electricName_adapter);
        sp_electricAssembly.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "电气部装id:-----"+spinnerBeanArrayList.get(position).getElectricId());
                electricAssemblyId = spinnerBeanArrayList.get(position).getElectricId();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

    }
    //    添加 设备编号
    public void setDeviceNumber(FactoryDeviceManagement device){
        API.addSerialNumber(device, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
               HomePageActivity.this.runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       System.out.println("--添加设备编号--:"+result);
                       JSONObject j = JSONObject.parseObject(result);
                       String msg = j.getString("msg");
                       long l = Long.parseLong(j.getString("code"));
                       if (l == 200){
                           ToastUtils.successShowLong(getApplicationContext(),"设备编号添加成功!");
                       }else {
                           ToastUtils.warnShowLong(getApplicationContext(),msg);
                       }
                   }
               });
            }
            @Override
            public void onFail(int statusCode) { }
        });
    }

    //    dp  转化为  像素
    public int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round((float) dp * density);
    }

    //  强制 关闭 软键盘
    public void closeEditText(EditText editText){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(),0);
    }

}